package com.loit.loitcommon.utils;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 模拟http请求工具类
 *
 * @author zhangyinglu
 */
public class HttpUtil {

    private final static Logger logger = LoggerFactory.getLogger(HttpUtil.class);


    public static String doGetUkString(String url, Map<String, String> map) {
        try {
            List<NameValuePair> params = map.entrySet().stream().map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue())).collect(Collectors.toList());
            URI uri = new URI(url + "?" + URLEncodedUtils.format(params, "UTF-8"));
            HttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(uri);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            String strResult = EntityUtils.toString(httpEntity, "UTF-8");
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                return strResult;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return null;
    }


    public static String doPostuKString(String url, String jsonString) {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            StringEntity stringEntity = new StringEntity(jsonString, "UTF-8");
            httpPost.setEntity(stringEntity);
//			httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            String strResult = EntityUtils.toString(httpEntity, "UTF-8");
            logger.info("请求返回码：" + httpResponse.getStatusLine().getStatusCode());
            logger.info("请求结果：" + strResult);
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                return strResult;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return null;
    }

    /**
     * Get请求String
     *
     * @param url 请求地址
     * @return String
     * @author zhangyinglu
     */
    public static String doGet4String(String url) {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                HttpEntity httpEntity = httpResponse.getEntity();
                String strResult = EntityUtils.toString(httpEntity, "UTF-8");

                return strResult;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return null;
    }

    /**
     * Get请求String
     *
     * @param url 请求地址
     * @param map 请求参数  应该是表单格式的参数
     * @return String
     * @author zhangyinglu
     */
    public static String doGet4String(String url, Map<String, String> map) {
        try {
            List<NameValuePair> params = map.entrySet().stream().map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue())).collect(Collectors.toList());
            URI uri = new URI(url + "?" + URLEncodedUtils.format(params, "UTF-8"));
            HttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(uri);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                HttpEntity httpEntity = httpResponse.getEntity();
                String strResult = EntityUtils.toString(httpEntity, "UTF-8");

                return strResult;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return null;
    }

    /**
     * Post请求返回String
     *
     * @param url 请求地址
     * @return String
     * @author zhangyinglu
     */
    public static String doPost4String(String url) {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                HttpEntity httpEntity = httpResponse.getEntity();
                String strResult = EntityUtils.toString(httpEntity, "UTF-8");
                return strResult;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return null;
    }

    /**
     * Post请求返回String
     *
     * @param url        请求地址
     * @param jsonString 请求参数
     * @return String
     * @author zhangyinglu
     */
    public static String doPost4String(String url, String jsonString) {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000).setSocketTimeout(3000).build();
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(jsonString, "UTF-8");
            httpPost.setEntity(stringEntity);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            logger.info("请求返回码：" + httpResponse.getStatusLine().getStatusCode());

            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                String strResult = EntityUtils.toString(httpEntity, "UTF-8");
                logger.info("请求结果：" + strResult);
                return strResult;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return null;
    }
    /**
     * Post请求返回String
     *
     * @param url        请求地址
     * @param jsonString 请求参数
     * @param headerMap  请求头
     * @return String
     * @author zhangyinglu
     */
    public static String doPost4String2(String url, String jsonString, Map<String, Object> headerMap) {
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000).setSocketTimeout(3000).build();
            httpPost.setConfig(requestConfig);
            StringEntity stringEntity = new StringEntity(jsonString, "UTF-8");
            httpPost.setEntity(stringEntity);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            if (headerMap != null) {
                for (String key : headerMap.keySet()) {
                    if (headerMap.get(key) != null) {
                        httpPost.addHeader(key, String.valueOf(headerMap.get(key)));
                    }
                }
            }
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            logger.info("请求返回码：" + httpResponse.getStatusLine().getStatusCode());

            if (HttpStatus.SC_OK == httpResponse.getStatusLine().getStatusCode()) {
                String strResult = EntityUtils.toString(httpEntity, "UTF-8");
                logger.info("请求结果：" + strResult);
                return strResult;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return null;
    }

    /**
     * Get请求返回Json
     *
     * @param url 请求地址
     * @return JSONObject
     * @author zhangyinglu
     */
    public static JSONObject doGet4Json(String url) {
        try {
            return JSONObject.parseObject(doGet4String(url));
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return null;
    }

    /**
     * Get请求返回Json
     *
     * @param url 请求地址
     * @param map 请求参数
     * @return JSONObject
     * @author zhangyinglu
     */
    public static JSONObject doGet4Json(String url, Map<String, String> map) {
        try {
            return JSONObject.parseObject(doGet4String(url, map));
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return null;
    }

    /**
     * Post请求返回Json
     *
     * @param url 请求地址
     * @return JSONObject
     * @author zhangyinglu
     */
    public static JSONObject doPost4Json(String url) {
        try {
            return JSONObject.parseObject(doPost4String(url));
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return null;
    }

    /**
     * Post请求返回Json
     *
     * @param url        请求地址
     * @param jsonString 请求参数
     * @return JSONObject
     * @author zhangyinglu
     */
    public static JSONObject doPost4Json(String url, String jsonString) {
        try {
            return JSONObject.parseObject(doPost4String(url, jsonString));
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

        return null;
    }

    /**
     * Post请求返回boolean
     *
     * @param url        请求地址
     * @param jsonString 请求参数
     * @return boolean
     * @author zhangyinglu
     */
    public static boolean doPost4Boolean(String url, String jsonString) {
        String result = doPost4String(url, jsonString);
        if (!StringUtils.isEmpty(result)) {
            Map<String, Object> map = JSONObject.parseObject(result, new TypeReference<Map<String, Object>>() {
            });
            if (map.get("code") != null) {
                if ("200".equals(String.valueOf(map.get("code")))) {
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * Post请求返回boolean
     *
     * @param url        请求地址
     * @param jsonString 请求参数
     * @param headerMap  请求头
     * @return boolean
     */
    public static boolean doPost4Boolean2(String url, String jsonString, Map<String, Object> headerMap) {
        String result = doPost4String2(url, jsonString, headerMap);
        if (!StringUtils.isEmpty(result)) {
            Map<String, Object> map = JSONObject.parseObject(result, new TypeReference<Map<String, Object>>() {
            });
            if (map.get("code") != null) {
                if ("200".equals(String.valueOf(map.get("code")))) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Get请求返回Xml<b>暂不支持</b>
     *
     * @param url 请求地址
     * @return JSONObject
     * @author zhangyinglu
     */
    public static String doGet4Xml(String url) {
        return null;
    }

    /**
     * Post请求返回Xml<b>暂不支持</b>
     *
     * @param url 请求地址
     * @return JSONObject
     * @author zhangyinglu
     */
    public static String doPost4Xml(String url) {
        return null;
    }

    public static void main(String[] args) {
        System.out.println(doGet4String("http://192.168.230.18:10098/httpproxy/getToken"));
    }
}
